package com.weibei.web.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @program: plat_cloud
 * @description: 砍价算法实现
 * @author: weibei
 * @date: 2020-06-03 17:25
 **/
public class BargainUtils {

    /**
     * 砍价算分
     * @param money 剩余的金额
     * @param count 最终平分数量
     * @param minS  最小值默认为 1
     * @param maxS  最大值默认为money
     * @return
     */
    public static int randomReducePrice(int money, int count, int minS, int maxS) {
        //若只有一个，直接返回
        if (count == 1) {
            return money;
        }
        //如果最大金额和最小金额相等，直接返回金额
        if (minS == maxS) {
            return minS;
        }
        int max = maxS > money? money : maxS;
        //分配砍价正确情况，允许砍价的最大值
        int maxY = money - (count - 1) * minS;
        //分配砍价正确情况，允许砍价最小值
        int minY = money - (count-1) * maxS;
        //随机产生砍价的最小值
        int min = minS > minY ? minS: minY;
        //随机产生砍价的最大值
        max = max > maxY ? maxY : max;
        //随机产生一个砍价
        return (int) Math.rint(Math.random()*(max - min) + min);
    }

    /**
     * 砍价算分
     * @param money
     * @param count
     * @return
     */
    public static List<Integer> splitReducePrice(int money, int count) {
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < count; i++){
            int one = randomReducePrice(money, count-i, 1, money);
            if (one < 0) {
                one = 0;
            }
            list.add(one);
            money -= one;
        }
        return list;
    }

    /**
     * 获取随机数最大值
     * @param totalPrice
     * @param count
     * @return
     */
    public static BigDecimal randomMax(BigDecimal totalPrice, int count) {
        BigDecimal multiple = new BigDecimal("100");
        BigDecimal multiplyMoney = totalPrice.multiply(multiple);
        int money = multiplyMoney.intValue();
        List<Integer> list = splitReducePrice(money, count);
        Integer max = Collections.max(list);
        BigDecimal bigDecimal1 = new BigDecimal(max);
        BigDecimal divide = bigDecimal1.divide(multiple,2, RoundingMode.HALF_UP);
        return divide;
    }
}
